﻿CREATE PROCEDURE [dbo].[RequisitionDocDelete]
(--Сводная заявка. Состоит из заказов товара у поставщиков
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intErrCode int, @intRet int, @orgDocTypeId int
DECLARE @intLineId int, @datLineMD datetime

SET NOCOUNT ON
IF (@Original_Id Is Null) OR (@Original_MD Is Null) 
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

SELECT @orgDocTypeId = DocTypeId 
FROM CA.Documents WHERE Id = @Original_Id AND MD = @Original_MD
IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @orgDocTypeId <> 13
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Неправильный тип документа!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END
--курсор на шапки заказов поставщикам
DECLARE OrderDocs CURSOR FAST_FORWARD FOR
SELECT Id, MD FROM CA.Documents WHERE ParentId = @Original_Id

OPEN OrderDocs

FETCH NEXT FROM OrderDocs INTO @intLineId, @datLineMD
BEGIN TRAN
WHILE (@@FETCH_STATUS = 0)
BEGIN

		EXEC @intRet = dbo.OrderDocDelete @intLineId, @datLineMD
	
		SET @intErrCode = @@error
		IF @intErrCode <> 0
		BEGIN 
			IF @@trancount > 0 ROLLBACK TRANSACTION
			CLOSE OrderDocs
			DEALLOCATE OrderDocs
			RETURN @intErrCode
		END
		
		IF @intRet <> 0
		BEGIN 
			IF @@trancount > 0 ROLLBACK TRANSACTION
			CLOSE OrderDocs
			DEALLOCATE OrderDocs
			RETURN @intRet
		END
	
	FETCH NEXT FROM OrderDocs INTO @intLineId, @datLineMD
END

CLOSE OrderDocs
DEALLOCATE OrderDocs

	SET NOCOUNT OFF;
DELETE FROM [CA].[Documents] WHERE Id = @Original_Id

SET @intErrCode = @@error
IF @intErrCode <> 0
BEGIN 
	IF @@trancount > 0 ROLLBACK TRANSACTION
	RETURN @intErrCode
END

COMMIT TRAN










